using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using NHibernate.Burrow;
using NHibernate.Burrow.Configuration;
using NHibernate.Burrow.Util;
using Ornament.MVCWebFrame.Models;
using Ornament.NHibernateHelper;
using Ornament.NHibernates.Configurations;
using Ornament.Web.Mvc;

namespace Ornament.MVCWebFrame.Controllers
{
    /// <summary>
    /// </summary>
    public class NHibernateController : Controller
    {
        /// <summary>
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <returns>
        /// </returns>
        public ActionResult Index(int? id)
        {
            // find cfgFile path;
            var cfgSection = (NHibernateBurrowCfgSection) ConfigurationManager.GetSection("NHibernate.Burrow");
            var fileSet =
                from cfgFile in cfgSection.PersistenceUnits.Cast<IPersistenceUnitCfg>()
                select new SelectListItem {Text = cfgFile.NHConfigFile, Value = cfgFile.NHConfigFile};

            var configFiles = fileSet.ToArray();
            configFiles[id ?? 0].Selected = true;
            ViewData["configFiles"] = configFiles;

            //find session factory Name           
            string filePath = Request.MapPath(configFiles[id ?? 0].Value);
            var nh = new NHibernateSetting(filePath);
            var sessionFactoryNames
                = from sfName in nh.GetSessionFactoryNames()
                  select new SelectListItem
                             {
                                 Text = sfName,
                                 Value = sfName,
                             };
            sessionFactoryNames.First().Selected = true;

            ViewData["sessionFactoryName"] = sessionFactoryNames;

            TempData["assembly"] = nh.FindNHibernateAssembly();
            return View();
        }

        /// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        public ActionResult GetseesionFactroy()
        {
            string sessionName = Request.QueryString["SessionFactoryName"];


            string filePath = Request.MapPath(Request.QueryString["filePath"]);

            var nh = new NHibernateSetting(filePath);
            SessionFactory s = nh[sessionName];
            return Json(s);
        }

        /// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        public ActionResult GetDriverClass()
        {
            string database = Request.QueryString["database"];
            return Json(DataBaseType.SupportDataBaseTypes[database]);
        }

        /// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        public ActionResult CreateTable()
        {
            try
            {
                var sc = new SchemaUtil();
                sc.DropSchemas(false, false);
                sc.CreateSchemas();
                var ss = new {Result = true};
                MemberShipContext.Initialize();

                return Json(ss);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }


        /// <summary>
        /// </summary>
        /// <param name="filePath">
        /// The file path.
        /// </param>
        /// <param name="sessionFactoryName">
        /// The session factory name.
        /// </param>
        /// <param name="sessionFactory">
        /// The session factory.
        /// </param>
        /// <returns>
        /// </returns>
        [JsonContainerFilter]
        public ActionResult Save(string filePath, string sessionFactoryName, JsonContainer sessionFactory)
        {
            var session = new NHibernateSetting(Request.MapPath(filePath));
            SessionFactory sessionFactorySetting = session[sessionFactoryName];

            sessionFactorySetting.DriverInfo.ConnectionProvider =
                sessionFactory.ToString("DriverInfo.ConnectionProvider");
            sessionFactorySetting.DriverInfo.ConnectionString = sessionFactory.ToString("DriverInfo.ConnectionString");
            sessionFactorySetting.DriverInfo.DataBase =
                DataBaseType.SupportDataBaseTypes[sessionFactory.ToString("DriverInfo.DataBase.Dialect")];
            sessionFactorySetting.DriverInfo.DriverClass = sessionFactory.ToString("DriverInfo.DriverClass");

            sessionFactorySetting.Runtime.BatchSize = sessionFactory.ToInt32("Runtime.BatchSize");
            sessionFactorySetting.Runtime.Isolation =
                (IsolationLevel) Enum.ToObject(typeof (IsolationLevel), sessionFactory.ToInt32("Runtime.Isolation"));

            sessionFactorySetting.Runtime.ShowSql = sessionFactory.ToBoolean("Runtime.ShowSql");
            sessionFactorySetting.Runtime.Timeout = sessionFactory.ToInt32("Runtime.Timeout");
            sessionFactorySetting.Runtime.UseOuterJoin = sessionFactory.ToBoolean("Runtime.UseOuterJoin");
            //Mappings
            sessionFactorySetting.Mappings.Clear();
            JsonContainer[] mappings = sessionFactory.ToArray<JsonContainer>("Mappings");
            foreach (JsonContainer item in mappings)
            {
                Mapping mapping = sessionFactorySetting.Mappings.CreateMapping();
                mapping.Assembly = item.ToString("Assembly");
                sessionFactorySetting.Mappings.Add(mapping);
            }
            session.Save();
            return Json("true");
        }
    }
}